package com.jzg.mvc.biz.cab.module;

import com.jfinal.core.Path;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jzg.common.controller.BaseController;
import com.jzg.common.model.biz.CabModule;
import com.jzg.common.model.biz.CabModuleBoard;
import com.jzg.common.util.UuidUtil;

@Path(value = "/biz/cab/module", viewPath = "/views/biz/cab/module")
public class CabModuleController extends BaseController {

	protected final Log LOG = Log.getLog(getClass());

	public void index() {
		this.setAttr("cabId", this.getPara("cabId"));
		render("list.html");
	}

	public void listData() {
		int pageNumber = getParaToInt("page", 1);
		int pageSize = getParaToInt("limit", 10);
		String keyword = getPara("keyword");
		String cabId = getPara("cabId");
		String sqlExceptSelect = " FROM " + CabModule.TABLE_NAME + " O  WHERE 1=1 ";
		if (!StrKit.isBlank(keyword)) {
			sqlExceptSelect += " AND ( O.NAME LIKE '%" + keyword + "%' OR   O.CODE '%" + keyword + "%' ) ";
		}
		if (!StrKit.isBlank(cabId)) {
			sqlExceptSelect += " AND O.cabId='"+cabId+"' ";
		}
		sqlExceptSelect += "  ORDER BY   O.SORT asc ";
		Page<CabModule> page = CabModule.dao.paginate(pageNumber, pageSize, "select * ", sqlExceptSelect);
		renderLayuiPage(0, page.getList(), "", page.getTotalRow());
	}

	/***
	 * 保存
	 */
	public void save() {
		CabModule cabModule = getModel(CabModule.class);
		if (StrKit.notBlank(cabModule.getId())) {
			CabModule module = CabModule.dao.findFirst("SELECT * FROM " + CabModule.TABLE_NAME + " WHERE CABID=? and TYPE=? AND ID!=?", cabModule.getCabId(),cabModule.getType(),cabModule.getId());
			if (module != null) {
				renderError("柜子组已存在！");
				return;
			}
			if (cabModule.update()) {
				renderSuccess("更新成功！");
			} else {
				renderError("更新失败！");
			}
		} else {
			CabModule module = CabModule.dao.findFirst("SELECT * FROM " + CabModule.TABLE_NAME + " WHERE CABID=? AND TYPE=? ", cabModule.getCabId(),cabModule.getType());
			if (module != null) {
				renderError("名称已存在！");
				return;
			}
			cabModule.setId(UuidUtil.getUUID());
			if (cabModule.save()) {
				renderSuccess("保存成功！");
			} else {
				renderError("保存失败！");
			}
		}

	}

	/***
	 * 删除
	 * @throws Exception
	 */
	public void delete() throws Exception {
		String id = getPara("id");
		CabModule cabModule = CabModule.dao.findById(id);
		if (cabModule != null) {
			if (cabModule.delete()) {
				Db.delete("delete from "+CabModuleBoard.TABLE_NAME+" where moduleId=?",cabModule.getId());
				renderSuccess("删除成功！");
			} else {
				renderError("删除失败！");
			}
		} else {
			renderError("数据不存在,请刷新后再试!");
		}
	}
	
}
